package com.army.study;

import com.army.study.database.Bus;
import com.army.study.database.BusComesDatabase;
import com.army.study.database.Form;
import com.army.study.database.Station;
import com.army.study.service.BusInternalAbility;
import com.army.study.service.TimerAbility;
import com.army.study.utils.DatabaseUtils;
import com.army.study.utils.LogUtils;
import com.army.study.widget.controller.*;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.ProviderFormInfo;
import ohos.aafwk.content.Operation;
import ohos.ace.ability.AceAbility;
import ohos.aafwk.content.Intent;
import ohos.data.DatabaseHelper;
import ohos.data.orm.OrmContext;
import ohos.data.orm.OrmPredicates;
import ohos.hiviewdfx.HiLog;

import java.util.ArrayList;
import java.util.List;

public class MainAbility extends AceAbility {
    public static final int DEFAULT_DIMENSION_2X2 = 2;
    private static final String TAG = MainAbility.class.getSimpleName();
    private static final int INVALID_FORM_ID = -1;

    private DatabaseHelper helper = new DatabaseHelper(this);
    private OrmContext connect;
    private String topWidgetSlice;


    @Override
    public void onStart(Intent intent) {
        LogUtils.info(TAG, "onStart...");
        connect = helper.getOrmContext("BusComesDatabase", "BusComesDatabase.db", BusComesDatabase.class);
        // 初始化数据
        System.out.println("**MainAbility-onStart...");
        initData();

        BusInternalAbility.getInstance().register();
        super.onStart(intent);
        if (intentFromWidget(intent)) {
            topWidgetSlice = getRoutePageSlice(intent);
            if (topWidgetSlice != null) {
                setMainRoute(topWidgetSlice);
            }
        }
        stopAbility(intent);

        // 启动TimerAbility
        Intent intentService = new Intent();
        Operation operation =
                new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName(getBundleName())
                        .withAbilityName(TimerAbility.class.getName())
                        .build();
        intentService.setOperation(operation);
        startAbility(intentService);
    }

    public List<Bus> getBusListByKeyword(String keyword) {
        if (connect == null) {
            connect = helper.getOrmContext("BusComesDatabase", "BusComesDatabase.db", BusComesDatabase.class);
        }

        LogUtils.info(TAG, "查找关键了是: " + keyword);
        List<Bus> result = DatabaseUtils.getBubsByKeyword(connect, keyword);
        return result;
    }

    public List<Station> getStationListByParentId(Long parentId) {
        if (connect == null) {
            connect = helper.getOrmContext("BusComesDatabase", "BusComesDatabase.db", BusComesDatabase.class);
        }

        LogUtils.info(TAG, "公交线路Id是: " + parentId);
        List<Station> result = DatabaseUtils.getStationByParentId(connect, parentId);
        return result;
    }

    /**
     * 绑定卡片和公交车关系
     * @param formId
     * @param busId
     */
    public void bindingCardById(Long formId, Long busId) {

        System.out.println("开始更新卡片...");
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        formController.updateFormData(formId, busId);

    }


    @Override
    public void onStop() {
        LogUtils.info(TAG, "onStop...");
        System.out.println("**MainAbility-onStop...");
        super.onStop();
//        if (connect != null) {
//            DatabaseUtils.deleteAllBusData(connect);
//        }
        BusInternalAbility.getInstance().unregister();
    }

    public void initData() {
        if (connect == null) {
            connect = helper.getOrmContext("BusComesDatabase", "BusComesDatabase.db", BusComesDatabase.class);
        }
        DatabaseUtils.insertList(connect);
        System.out.println("已初始化完公交车信息......");
    }



    @Override
    protected ProviderFormInfo onCreateForm(Intent intent) {
        LogUtils.info(TAG, "onCreateForm");
        long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
        String formName = intent.getStringParam(AbilitySlice.PARAM_FORM_NAME_KEY);
        int dimension = intent.getIntParam(AbilitySlice.PARAM_FORM_DIMENSION_KEY, DEFAULT_DIMENSION_2X2);
        LogUtils.info(TAG, "onCreateForm: formId=" + formId + ",formName=" + formName);
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        formController = (formController == null) ? formControllerManager.createFormController(formId,
                formName, dimension) : formController;
        if (formController == null) {
            LogUtils.error(TAG, "Get null controller. formId: " + formId + ", formName: " + formName);
            return null;
        }

        // 保存卡片信息
        if (connect == null) {
            connect = helper.getOrmContext("BusComesDatabase", "BusComesDatabase.db", BusComesDatabase.class);
        }
        Form form = new Form(formId,formName, dimension, 1L);
        DatabaseUtils.insertForm(connect, form);
        System.out.println("开始保存卡片到数据库");
        System.out.println("卡片Id: " + formId + ", 卡片名: " + formName + ", 规格: " + dimension + ", 公交车Id: " + 1L);
        System.out.println("结束保存卡片到数据库");

        return formController.bindFormData();
    }

    @Override
    protected void onUpdateForm(long formId) {
        LogUtils.info(TAG, "onUpdateForm");
        super.onUpdateForm(formId);
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        formController.updateFormData(formId);
    }

    @Override
    protected void onDeleteForm(long formId) {
        LogUtils.info(TAG, "onDeleteForm: formId=" + formId);
        super.onDeleteForm(formId);
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        formControllerManager.deleteFormController(formId);
        // 删除卡片信息
        if (connect == null) {
            connect = helper.getOrmContext("BusComesDatabase", "BusComesDatabase.db", BusComesDatabase.class);
        }
        DatabaseUtils.deleteFormData(connect, formId);
    }

    @Override
    protected void onTriggerFormEvent(long formId, String message) {
        LogUtils.info(TAG, "onTriggerFormEvent: " + message);
        super.onTriggerFormEvent(formId, message);
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        formController.onTriggerFormEvent(formId, message);
    }

    @Override
    public void onNewIntent(Intent intent) {
        if (intentFromWidget(intent)) { // Only response to it when starting from a service widget.
            String newWidgetSlice = getRoutePageSlice(intent);
            if (topWidgetSlice == null || !topWidgetSlice.equals(newWidgetSlice)) {
                topWidgetSlice = newWidgetSlice;
                restart();
            }
        }
    }

    private boolean intentFromWidget(Intent intent) {
        long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
        return formId != INVALID_FORM_ID;
    }

    private String getRoutePageSlice(Intent intent) {
        long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
        if (formId == INVALID_FORM_ID) {
            return null;
        }
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        if (formController == null) {
            return null;
        }
        Class<? extends AbilitySlice> clazz = formController.getRoutePageSlice(intent);
        if (clazz == null) {
            return null;
        }
        return clazz.getName();
    }
}
